package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Value("${redirect_uri}")
    private String redirect_uri;
    @Value("${client_id}")
    private String client_id;
    @Value("${client_secret}")
    private String client_secret;
    @Value("${gitee_authorize_url}")
    private String gitee_authorize_url;
    @Value("${gitee_token_url}")
    private String gitee_token_url;

    @Autowired
    private RestTemplate restTemplate;

    @ResponseBody
    @GetMapping("/hello")
    public Object hello(){
        return "hello";
    }
    //http://localhost:8080/index
    @GetMapping("/index")
    public String index(HttpServletRequest request){
        final Object user = request.getSession().getAttribute("user");
        if(user == null){
            //request.getSession().setAttribute("user","user");
            //https://gitee.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code
            gitee_authorize_url = gitee_authorize_url.replace("{client_id}",client_id).replace("{redirect_uri}",redirect_uri);
            return "redirect:"+gitee_authorize_url;
        }
        return "center.html";
    }

    @GetMapping("/code")
    @ResponseBody
    public String code(
            @RequestParam("code") String code
            , HttpServletRequest request
    ){
        //https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
        gitee_token_url = gitee_token_url
                .replace("{code}",code)
                .replace("{client_id}",client_id)
                .replace("{redirect_uri}",redirect_uri)
                .replace("{client_secret}",client_secret)
        ;

        Map<String, Object> resultMap = new HashMap<>(5);
        String result = restTemplate.postForObject(gitee_token_url, resultMap, String.class);

        return result;
    }

}
